<?php

namespace app\admin\controller;

use app\service\AjaxResponse;
use app\service\GuanyiService;
use app\service\RpcClient;
use think\Exception;
use think\Lang;
use think\Request;

/**
 * ============================================================================
 * 佳皿一站式,酒水服务类综合平台
 * ============================================================================
 * 版权所有 2019-2028 成都佳皿商贸有限公司，并保留所有权利。
 * 网站地址: http://www.91buys.com
 * ============================================================================
 * 控制器
 */
class Order extends AdminControl {

    const EXPORT_SIZE = 1000;
    const SYNC_QIANHAI_ERROR    = 3;
    const SYNC_QIANHAI_SUCCESS  = 2;

    const SEND_HAIGUAN_ERROR    = 3;
    const SEND_HAIGUAN_SUCCESS  = 2;


    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/'.config('default_lang').'/order.lang.php');
    }

    public function index() {
        $order_model = model('order');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }
        $store_name = input('param.store_name');
        if ($store_name) {
            $condition['store_name'] = $store_name;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '10', '20', '30', '40'))) {
            $condition['order_state'] = $order_state;
        }
        $payment_code = input('param.payment_code');
        if ($payment_code) {
            $condition['payment_code'] = $payment_code;
        }
        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['buyer_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        $order_list = $order_model->getOrderList($condition, 10);
        $this->assign('show_page', $order_model->page_info->render());

        //订单ID编号
        $sucessOrderIds = $orderIds = [];
        foreach ($order_list as $order_id => $order_info) {
            array_push($orderIds,$order_info['order_id']);
            //显示取消订单
            $order_list[$order_id]['if_cancel'] = $order_model->getOrderOperateState('system_cancel', $order_info);
            //显示收到货款
            $order_list[$order_id]['if_system_receive_pay'] = $order_model->getOrderOperateState('system_receive_pay', $order_info);
        }
        //查询订单是否有,管易同步成功记录
        if(!empty($orderIds)){
            $orderIdsStr = implode(',',$orderIds);
            $gunyiOrderSuccessLog   = (new GuanyiService())->getOrderSyncGuanyiRow(['order_id'=>['in',$orderIds],'error_code'=>'success'],'order_id');
            $sucessOrderIds         = array_column($gunyiOrderSuccessLog,'order_id');

            $this->assign('sucessOrderIds',$sucessOrderIds);
        }
        //显示支付接口列表(搜索)
        $payment_list = model('payment')->getPaymentOpenList();
        $this->assign('payment_list', $payment_list);
        $this->assign('order_list', $order_list);
        
        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('add');
        return $this->fetch('index');
    }

    /**
     * 同步管易订单物流单号至 e驾优选平台 && 并执行发货操作
     * @param Request $request
     */
    public function syncGuanyiDeliverToPlat(Request $request){
        if(!$request->isPost()) ds_json_encode(10001,lang('request_type_err'));
        $orderId = (int)$request->post('order_id',0);    #订单ID编号

        if(empty($orderId)) ds_json_encode(10001,lang('params_err'));
        $guanyiServiceObj = new GuanyiService();
        //通过order_id获取到 当前订单同步至 管易的订单编号【表：ds_sync_order_guanyi_log】
        $condition['order_id'] = $orderId;
        $orderSyncGuanyiInfo   = $guanyiServiceObj->getOrderSyncGuanyiItem($condition,'id,token_code');

        if(empty($orderSyncGuanyiInfo)) ds_json_encode(10001,lang('erp_order_null'));
        if(empty($orderSyncGuanyiInfo['token_code']))   ds_json_encode(10001,lang('erp_not_found_guanyi_code'));

        $res = (new GuanyiService())->getInvoiceInfo($orderId,$orderSyncGuanyiInfo['token_code']);

        #if($res['success'] == 'false')    ds_json_encode(10001,lang('erp_sync_error'));
        if($res['success'] == 'false')    ds_json_encode(10001,$res['errorDesc']);

        ds_json_encode(10000,'success!');
    }
    /**
     * 同步跨境红酒至 前海酒加
     * @param Request $request
     */
    public function syncOrderToQianHai(Request $request)
    {
        if(!$request->isPost()) ds_json_encode(10001,lang('request_type_err'));
        $orderId = (int)$request->post('order_id',0);    #订单ID编号
        //获取订单商品信息，并获取该商品的库存。【主要是验证当前SKU的可用性】
        $orderGoodsInfo = model('order')->getOrdergoodsInfo(['order_id'=>$orderId],'goods_id,goods_num,goods_price');

        if(empty($orderGoodsInfo['goods_id']))  ds_json_encode(10001,lang('goods_info_err'));
        //获取该跨境商品的SKU，调用前海酒加的 库存API，验证SKU的可用性
        $goodsInfo = model('goods')->getGoodsInfo(['goods_id'=>$orderGoodsInfo['goods_id']],'goods_serial');

        if(empty($goodsInfo['goods_serial']))   ds_json_encode(10001,lang('goods_sku_err'));
        //RPC调用前海库存API
        $apiUrl = config('h5_rpc_route.get_qianhai_rpc');	#RPC服务端API
        $rpcClientObj = new RpcClient($apiUrl);
        try{
            $res = $rpcClientObj->getGoodsSku(['sku'=>$goodsInfo['goods_serial']]);
            $resArr = json_decode($res,true);

            if($resArr['code'] == 200 && $resArr['goods_storage'] == 0)  return  AjaxResponse::ajax_error('Goods Storage Must Gt 0!');
            //同步订单至前海【前海跨境商品，仅支持单品下单】
            $goodsList = [
                'goods_sku'     => $goodsInfo['goods_serial'],
                'goods_price'   => $orderGoodsInfo['goods_price'],
                'goods_num'     => $orderGoodsInfo['goods_num']
            ];

            return  $this->_syncOrderDataToQianhai($orderId,$goodsList);
        }catch (Exception $e){
            return  AjaxResponse::ajax_error($e->getMessage());
        }
    }

    private function _syncOrderDataToQianhai($orderId = 0,$goodsList = [])
    {
        //根据OrderId 获取订单相关信息
        $orderList = [];
        //获取收货人信息
        $field = "pay_sn,buyer_name,payment_time,add_time,payment_code,goods_amount,order_amount,shipping_fee";
        $orderCommonInfo = model('order')->getOrderInfo(['order_id'=>$orderId],['order_common']);

        if(empty($orderCommonInfo)) return  AjaxResponse::ajax_error('OrderInfo Not Found！');
        //获取order对应order_pay表中：out_trade_no【平台调用支付接口时,统一下单接口时的对外订单号】，trade_no【第三方支付平台返回的交易单号】
        $orderPayInfo = model('order')->getOrderpayInfo(['pay_sn'=>$orderCommonInfo['pay_sn']]);

        if(empty($orderPayInfo))    return  AjaxResponse::ajax_error('OrderPay Info Not Found！');
        if(empty($orderPayInfo['out_trade_no']) || empty($orderPayInfo['trade_no']))    return  AjaxResponse::ajax_error('OrderPay TRADE_NO Not Empty！');
        //组装接口所需数据
        try{
            //省市区。area：北京 北京市 西城区【三级】
            $areaArr = explode(' ',$orderCommonInfo['extend_order_common']['reciver_info']['area']);

            $orderList = [
                //Todo ：发起三方支付的交易单号
                //'pay_sn'    => $orderCommonInfo['pay_sn'],
                'pay_sn'    => $orderPayInfo['out_trade_no'], #统一下单接口时的对外订单号
                'add_time'  => $orderCommonInfo['add_time'],
                'buyer_name'=> $orderCommonInfo['buyer_name'],
                'payment_time' => $orderCommonInfo['payment_time'],
                'payment_code' => $orderCommonInfo['payment_code'],
                'goods_amount' => $orderCommonInfo['goods_amount'],
                'order_amount' => $orderCommonInfo['order_amount'],
                'shipping_fee' => $orderCommonInfo['shipping_fee'],
//                'true_name'    => $orderCommonInfo['extend_order_common']['reciver_name'],
                'true_name'    => $orderCommonInfo['true_name'],
                'identity_card'=> $orderCommonInfo['buyer_id_card'],
                'reciver_name' => $orderCommonInfo['extend_order_common']['reciver_name'],
                'mob_phone'     => $orderCommonInfo['extend_order_common']['reciver_info']['phone'],
                'province_name' => $areaArr[0], #省
                'city_name'     => $areaArr[1], #市
                'area_name'     => $areaArr[2], #区
                'address_info'  => $orderCommonInfo['extend_order_common']['reciver_info']['street'],
                'order_message' => $orderCommonInfo['extend_order_common']['order_message'],
                //TODO:三方交易ID编号
                'paytransactionid'=> $orderPayInfo['trade_no'],
            ];
            $orderList['goods_list'][0] = $goodsList;


            //准备payment 推送数据 --开始
            $pushdata_model=model("pushdata");
            $where1=array(
                "order_id"=>$orderId,
            );
            $pushdata=$pushdata_model->getpushdata($where1);
            if(empty($pushdata)) return  AjaxResponse::ajax_error('pushdata Not Found！');
            $pushdata=$pushdata[0];
            $orderpay_model=model("order");
            $where2=array(
                "out_trade_no"=>$pushdata['pay_sn'],
            );
            $Orderpaydata=$orderpay_model->getOrderpayInfo($where2);
            if(empty($Orderpaydata)) return  AjaxResponse::ajax_error('orderpay data Not Found！');

            $pushdata['trade_no']=$Orderpaydata['trade_no'];

            //准备payment 推送数据 --结束


            //RPC调用前海，下单API
            $apiUrl = config('h5_rpc_route.get_qianhai_rpc');	#RPC服务端API
            $rpcClientObj = new RpcClient($apiUrl);

          $res = $rpcClientObj->syncOrderToJiuJia(['order_list'=>$orderList]);

            $res = $rpcClientObj->syncPaymentToJiuJia(['payment_data'=>$pushdata]);


            $resArr = json_decode($res,true);

            if($resArr['code'] != 200) { #更新订单同步前海状态：失败
                model('order')->editOrder(['sync_to_border'=>self::SYNC_QIANHAI_ERROR],['order_id' => $orderId]);

                return  AjaxResponse::ajax_error($resArr['message']);
            }
            if($resArr['code'] == 200) { #更新订单同步前海状态：成功
                model('order')->editOrder(['sync_to_border'=>self::SYNC_QIANHAI_SUCCESS],['order_id' => $orderId]);

                return  AjaxResponse::ajax_success('Success！');
            }

        }catch (Exception $e){
            return  AjaxResponse::ajax_error($e->getMessage());
        }
    }
    /**
     * 海关申报
     * @param Request $request
     */
    public function sendToHaiguan(Request $request){
        if(!$request->isPost()) ds_json_encode(10001,lang('request_type_err'));
        $orderId = (int)$request->post('order_id',0);    #订单ID编号
        if(empty($orderId)) ds_json_encode(10001,lang('params_err'));
        //获取推送信息的xml数据
        $condition=array();
        $condition["order_id"]=$orderId;
        $res= $pushdataModel=model('pushdata')->getpushdata($condition,'initalResponse');
        if(!empty($res)){
            $xmls= $res[0]["initalResponse"];
        }


        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xmls, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //准备新的数据，去掉不需要的参数

        $new_arr=array();

        $new_arr["appid"]=$arr['appid'];
        $new_arr["mch_id"]=$arr['mch_id'];
        $new_arr["out_trade_no"]=$arr['out_trade_no'];
        $new_arr["transaction_id"]=$arr['transaction_id'];
        $new_arr["customs"]="SHENZHEN";
        $new_arr["mch_customs_no"]="5101960A6J";
        //准备签名
        $stringA="appid={$arr['appid']}&customs=SHENZHEN&mch_customs_no=5101960A6J&mch_id={$arr['mch_id']}&out_trade_no={$arr['out_trade_no']}&transaction_id={$arr['transaction_id']}";

        $stringSignTemp=$stringA."&key=jmsm8888jmsm8888jmsm8888jmsm8888";
//         var_dump($stringSignTemp);die;
        $sign=strtoupper(MD5($stringSignTemp));
        $new_arr["sign"]=$sign;

        $xml=arrayToXml($new_arr);

        $url="https://api.mch.weixin.qq.com/cgi-bin/mch/customs/customdeclareorder";
        $result=http_post($url, $xml);

        $info = json_decode(json_encode(simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if($info['return_code'] != 'SUCCESS') { #更新订单同步前海状态：失败
            model('order')->editOrder(['send_to_haiguan'=>self::SEND_HAIGUAN_ERROR],['order_id' => $orderId]);

            return  AjaxResponse::ajax_error($info['return_msg']);
        }
        if($info['return_code'] =='SUCCESS') { #更新订单同步前海状态：成功
            model('order')->editOrder(['send_to_haiguan'=>self::SEND_HAIGUAN_SUCCESS],['order_id' => $orderId]);

            return  AjaxResponse::ajax_success('Success！');
        }

    }
    /**
     * 同步商城订单 至 管易
     * @param Request $request
     */
    public function syncOrderToGuanYi(Request $request)
    {
        if(!$request->isPost()) ds_json_encode(10001,lang('request_type_err'));
        $orderId = (int)$request->post('order_id',0);    #订单ID编号

        if(empty($orderId)) ds_json_encode(10001,lang('params_err'));
        //根据订单ID编号，获取同步管易需要的信息
        $orderItemInfo = model('order')->getOrderInfo(['order_id'=>$orderId],['order_common','order_goods']);
        //订单扩展信息
        if(empty($orderItemInfo))   ds_json_encode(10000,lang('data_null'));
        //组装 同步管易的数据
        $args = [];
        $args['order_id']       = $orderId;  #当前同步至管易的订单ID编号，便于记录同步的结果日志
        $args['receiver_name']  = $orderItemInfo['extend_order_common']['reciver_name'];  #收货人名字
        $args['buyer_memo']     = $orderItemInfo['extend_order_common']['order_message']; #订单备注
        $args['deal_datetime']  = $orderItemInfo['add_time'];     #订单下单时间
        $args['receiver_mobile']= $orderItemInfo['extend_order_common']['reciver_info']['mob_phone'];     #收货人手机号码
        $args['receiver_address']= $orderItemInfo['extend_order_common']['reciver_info']['address'];     #收货人手机号码
        //处理收货人的 省市区
        $receiverArea = $orderItemInfo['extend_order_common']['reciver_info']['area'];
        $areaArr = explode(' ',$receiverArea);

        $args['receiver_province']  = isset($areaArr[0]) && !empty($areaArr[0]) ? $areaArr[0] : '';     #收货人所在省级城市
        $args['receiver_city']      = isset($areaArr[1]) && !empty($areaArr[1]) ? $areaArr[1] : '';     #收货人所在市级城市
        $args['receiver_district']  = isset($areaArr[2]) && !empty($areaArr[2]) ? $areaArr[2] : '';     #收货人所在区、县级城市
        //商品明细
        $itemData = [];
        if(!empty($orderItemInfo['extend_order_goods'])){
            foreach ($orderItemInfo['extend_order_goods'] as $k=>$goodsItem){
                $itemData[$k]['item_code']  = "";  #商品对应的供应商货号
                //根据商品的goods_id，获取对应的goods_common_id所对应的货号
                $goodsCommonInfo = model('Goods')->getItemGoodsByCondition(['goods_id'=>$goodsItem['goods_id']],'goods_commonid');
                //获取goods_commonid对应的，商品货号
                if(!empty($goodsCommonInfo)) {
                    $goodsCommonArr = model('Goods')->getGoodsCommonList(['goods_commonid'=>$goodsCommonInfo['goods_commonid']],'goods_serial');

                    if(empty($goodsCommonArr[0]['goods_serial']))  ds_json_encode(10001,lang('goods_code_not_null'));
                    #TODO：由于管易对接其他仓库，导致商品代码不一定都按照青白江仓库的规则。故取消。
                    //if(strpos($goodsCommonArr[0]['goods_serial'],'jm') === false)   ds_json_encode(10001,lang('goods_code_not_correct'));

                    $itemData[$k]['item_code'] = $goodsCommonArr[0]['goods_serial'];
                }

                $itemData[$k]['price']      = $goodsItem['goods_price'];  #订单对应商品的价格
                $itemData[$k]['qty']        = $goodsItem['goods_num'];    #订单对应商品的数量
            }
        }
        //支付明细
        $paymentData['payment'] = isset($orderItemInfo['order_amount']) && !empty($orderItemInfo['order_amount']) ? $orderItemInfo['order_amount'] : 0;
        $paymentData['pay_type_code'] = 'balance';   #默认为预存款

        if($orderItemInfo['payment_code'] == 'alipay' || $orderItemInfo['payment_code'] == 'alipay_h5') $paymentData['pay_type_code'] = 'zfb';   #更改为支付宝
        if($orderItemInfo['payment_code'] == 'wxpay_h5' || $orderItemInfo['payment_code'] == 'wxpay_jsapi' || $orderItemInfo['payment_code']== 'wxpay_native') $paymentData['pay_type_code'] = 'wx';   #更改为微信
        //发票，暂时开不了。TODO：$invoiceData
        $invoiceData = [];
        //开始同步管易
        $res = (new GuanyiService())->orderToErpAdd($args,$itemData,$paymentData,$invoiceData);

        if($res['success'] != false)    ds_json_encode(10000,'sucess！');

        ds_json_encode(10001,$res['errorDesc']);
    }
    /**
     * 平台订单状态操作
     *
     */
    public function change_state() {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');

        //获取订单详细
        $condition = array();
        $condition['order_id'] = $order_id;
        $order_info = $order_model->getOrderInfo($condition);

        $state_type = input('param.state_type');
        if ($state_type == 'cancel') {
            $result = $this->_order_cancel($order_info);
            if (!$result['code']) {
                $this->error($result['msg']);
            } else {
                ds_json_encode(10000, $result['msg']);
            }
        } elseif ($state_type == 'receive_pay') {
            $result = $this->_order_receive_pay($order_info, input('post.'));
            if (!$result['code']) {
                $this->error($result['msg']);
            } else {
                dsLayerOpenSuccess($result['msg'],'Order/index');
            }
        }
    }

    /**
     * 系统取消订单
     */
    private function _order_cancel($order_info) {
        $order_id = $order_info['order_id'];
        $order_model = model('order');
        $logic_order = model('order','logic');
        $if_allow = $order_model->getOrderOperateState('system_cancel', $order_info);
        if (!$if_allow) {
            return ds_callback(false, '无权操作');
        }
        $result = $logic_order->changeOrderStateCancel($order_info, 'system', $this->admin_info['admin_name']);
        if ($result['code']) {
            $this->log(lang('order_log_cancel') . ',' . lang('order_number') . ':' . $order_info['order_sn'], 1);
        }
        return $result;
    }

    /**
     * 系统收到货款
     * @throws Exception
     */
    private function _order_receive_pay($order_info, $post) {
        $order_id = $order_info['order_id'];
        $order_model = model('order');
        $logic_order = model('order','logic');
        $if_allow = $order_model->getOrderOperateState('system_receive_pay', $order_info);
        if (!$if_allow) {
            return ds_callback(false, '无权操作');
        }

        if (!request()->isPost()) {
            $this->assign('order_info', $order_info);
            //显示支付接口列表
            $payment_list = model('payment')->getPaymentOpenList();
            //去掉预存款和货到付款
            foreach ($payment_list as $key => $value) {
                if ($value['payment_code'] == 'predeposit' || $value['payment_code'] == 'offline') {
                    unset($payment_list[$key]);
                }
            }
            $this->assign('payment_list', $payment_list);
            echo $this->fetch('receive_pay');
            exit;
        } else {
            $order_list = $order_model->getOrderList(array('pay_sn' => $order_info['pay_sn'], 'order_state' => ORDER_STATE_NEW));
            $result = $logic_order->changeOrderReceivePay($order_list, 'system', $this->admin_info['admin_name'], $post);
            if ($result['code']) {
                $this->log('将订单改为已收款状态,' . lang('order_number') . ':' . $order_info['order_sn'], 1);
            }
            return $result;
        }
    }

    /**
     * 查看订单
     *
     */
    public function show_order() {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');
        $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods', 'order_common', 'store'));

        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退款退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['seller_state'] = 2;
        $condition['admin_time'] = array('gt', 0);
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $refund_list = $refundreturn_model->getRefundList($condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }
        $this->assign('order_info', $order_info);
        return $this->fetch('show_order');
    }

    /**
     * 导出
     *
     */
    public function export_step1() {

        $order_model = model('order');
        $condition = array();
        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }
        $store_name = input('param.store_name');
        if ($store_name) {
            $condition['store_name'] = $store_name;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '10', '20', '30', '40'))) {
            $condition['order_state'] = $order_state;
        }
        $payment_code = input('param.payment_code');
        if ($payment_code) {
            $condition['payment_code'] = $payment_code;
        }
        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['buyer_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        if (!is_numeric(input('param.curpage'))) {
            $count = $order_model->getOrderCount($condition);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) { //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[$i] = $limit1 . ' ~ ' . $limit2;
                }
                $this->assign('export_list', $export_list);
                return $this->fetch('/public/excel');
            } else { //如果数量小，直接下载
                $data = $order_model->getOrderList($condition, '', '*', 'order_id desc', self::EXPORT_SIZE,['order_common','order_goods','store']);
                $this->createExcel($data);
            }
        } else { //下载
            $limit1 = (input('param.curpage') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $data = $order_model->getOrderList($condition, '', '*', 'order_id desc', "{$limit1},{$limit2}",['order_common','order_goods','store']);
            $this->createExcel($data);
        }
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array()) {
        Lang::load(APP_PATH .'admin/lang/'.config('default_lang').'/export.lang.php');
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_no'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_state'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_source'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_xtimd'));//下单时间
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_payment'));//付款时间
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_finnshed'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_paytype'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_pay_sn'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_goods_amount'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_shipping_fee'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_discount_type'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_product_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_product_sum'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_product_total'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_reciver_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_reciver_tel'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_reciver_province'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_reciver_city'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_reciver_area'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_reciver_address'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_order_message'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_buyer_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_buyer_tel'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_refund_type'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_tk_order_refund'));
        $member_model=model('member');
        //data
        foreach ((array) $data as $k => $v) {
            $tmp = array();
            $tmp[] = array('data' => 'DS' . $v['order_sn']);
            $tmp[] = array('data' => $v['state_desc']);
            $tmp[] = array('data' => get_from_state($v));
            $tmp[] = array('data' => $v['add_time']===0?'':date('Y-m-d H:i:s', $v['add_time']));
            $tmp[] = array('data' => $v['payment_time']===0?'':date('Y-m-d H:i:s', $v['payment_time']));
            $tmp[] = array('data' => $v['finnshed_time']===0?'':date('Y-m-d H:i:s', $v['finnshed_time']));
            $tmp[] = array('data' => $v['payment_name']);
            $tmp[] = array('data' => $v['pay_sn']);
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['goods_amount']));
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['shipping_fee']));
            $tmp[] = array('data' => is_null($v['extend_order_common']['voucher_price'])?'':'优惠卡券(-'.$v['extend_order_common']['voucher_price'].')');
            $tmp[] = array('data' => implode(',',array_column($v['extend_order_goods'],'goods_name')));
            $tmp[] = array('data' => count($v['extend_order_goods']));
            $tmp[] = array('data' => array_sum(array_column($v['extend_order_goods'],'goods_num')));
            $tmp[] = array('data' => $v['extend_order_common']['reciver_name']);
            $tmp[] = array('data' => $v['extend_order_common']['reciver_info']['mob_phone']);
            $explode_str=mb_strpos($v['extend_order_common']['reciver_info']['area'],',')!==false?',':' ';
            $area_arr=explode($explode_str,$v['extend_order_common']['reciver_info']['area']);
            $tmp[] = array('data' => isset($area_arr[0])?$area_arr[0]:'');
            $tmp[] = array('data' => isset($area_arr[0])?$area_arr[0]:'');
            $tmp[] = array('data' => isset($area_arr[0])?$area_arr[0]:'');
            $tmp[] = array('data' => $v['extend_order_common']['reciver_info']['street']);
            $tmp[] = array('data' => $v['extend_order_common']['order_message']);
            $tmp[] = array('data' => $v['buyer_name']);
            $tmp[] = array('data' => $member_model->getMemberInfoByID($v['buyer_id'])['member_mobile']);
            $tmp[] = array('data' => get_refund_state($v));
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['refund_amount']));
            $excel_data[] = $tmp;
        }

        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset(lang('exp_od_order'), CHARSET));
        $excel_obj->generateXML($excel_obj->charset(lang('exp_od_order'), CHARSET) . input('param.curpage') . '-' . date('Y-m-d-H', time()));
    }

}
